/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @return {TreeNode}
 */
export var inorderSuccessor = function (root, p) {
  const stack = []
  function dfs(node) {
    if (!node) return null
    let ans = dfs(node.left)
    if (ans) return ans
    if (stack.length && stack[stack.length - 1].val === p.val) {
      return node
    }
    stack.push(node)
    return dfs(node.right)
  }
  return dfs(root)
}
